let util = require('../../utils/util')
let p

Page({

    data: {
        staticDomain: util.config('staticDomain'),
        storeId: '',
        orderType: 0,
        orderGoodsList: {},
        payMode: 0,
        orderRemark: '',
        payBtnDisabled: true,
    },

	temp: {
		storeId: '',
		tableNum: '',
		orderId: '',
		status: {
			orderSubmitting: false
		}
	},

    onLoad: function () {
		p = this
		const orderData = util.globalData('orderDataTemp')
		console.log(orderData)
		if (!orderData || orderData.storePayMode == '') {
			util.showPanelErr({
				p,
				icon: 'failed',
				msg: '数据错误',
				use: '请返回上一层点餐',
				title: '数据错误'
			})
			return
		}
		const { storeId, storeName, storePayMode, tableNum, orderGoodsList, orderAttachList} = orderData
		wx.setNavigationBarTitle({
			title: `提交订单 | ${tableNum}`
		})
		p.temp.storeId = storeId
		p.temp.tableNum = tableNum
		p.temp.storePayMode = storePayMode.split(',')
		p.setData({
			storeId,
			payMode: p.temp.storePayMode[0],
			orderGoodsList: orderGoodsList.concat(orderAttachList.filter((attach) => {
				return attach.goodsCategory == 'must'
			})),
			orderAttachList
		})
    },

    onShow: () => {
        let chooseCoupon = util.globalData('couponTemp')
        let orderRemark = util.globalData('orderRemarkTemp')
        if (chooseCoupon && chooseCoupon.couponId && chooseCoupon.couponName && chooseCoupon.couponData) {
            let { orderGoodsTotal, orderCouponMoney } = p.data
            p.setData({
                orderCoupon: chooseCoupon
            })
            p.refreshOrderTotal()
        }
        else if (chooseCoupon) {
            p.setData({
                orderCoupon: {}
            })
            p.refreshOrderTotal()
        }
		if (util.isString(orderRemark)) 
            p.setData({
                orderRemark: orderRemark
            })
		else if (p.data.orderRemark == '' && orderRemark === false)
			p.setData({
				orderRemark: ''
			})
    },

	//附加物品勾选状态改变
	changeAttachNeed: (e) => {
		const attachIndex = e.currentTarget.dataset.attachindex
		let { orderGoodsList, orderAttachList } = p.data
		const { goodsId, goodsName, goodsCategory, goodsSpec} = orderAttachList[attachIndex]
		if (goodsCategory == 'must') {
			return
		}
		for (let i = 0;i < orderGoodsList.length;i++) {
			if (orderGoodsList[i].goodsId == goodsId) {
				orderGoodsList.splice(i, 1)
				p.setData({
					orderGoodsList
				})
				return
			}
		}
		orderGoodsList.push({
			goodsId,
			goodsCategory,
			goodsName,
			goodsCount: 1,
			goodsPrice: goodsSpec
		})
		p.setData({
			orderGoodsList
		})
	},

    //选择支付方式(目前只有现金和微信)
    choosePayMode: () => {
		let payModeList = []
		for (let mode of p.temp.storePayMode) {
			payModeList.push(['现金支付', '微信支付'][mode])
		}
        wx.showActionSheet({
			itemList: payModeList,
            success: (res) => {
				if (!res.tapIndex && res.tapIndex != 0) {
                    return
                }
                p.setData({
                    payMode: res.tapIndex
                })
            }
        })
    },

    goOrderRemark: () => {
        util.goPage('orderRemark', {
            content: p.data.orderRemark
        })
    },
    
    //支付订单
    payOrder: (e) => {
		if (p.temp.status.orderSubmitting)
			return
		const formId = e.detail.formId
		const { orderGoodsList, payMode, orderRemark } = p.data
		const {storeId, tableNum} = p.temp
		p.temp.status.orderSubmitting = true
		util.loading('提交中')
		let orderGoodsData = {}
		for (let goods of orderGoodsList) {
			if (!orderGoodsData[goods.goodsId])
				orderGoodsData[goods.goodsId] = []
			const { goodsCount, goodsPrice, chooseGoodsSpec } = goods
			orderGoodsData[goods.goodsId].push({
				goodsCount,
				goodsPrice,
				chooseGoodsSpec
			})
		}
		util.request({
			method: 'post',
			uri: 'order/wxapp',
			data: (p.temp.orderId && payMode == 1) ? {
				orderId: p.temp.orderId,
				orderPayMode: 1,
				session: util.globalData('session')
			} : {
				storeId,
				tableNum,
				orderPayMode: payMode, 
				orderCouponData: {},
				orderGoodsData,
				orderRemark,
				formId,
				session: util.globalData('session')
			},
			success: (data) => {
				const { orderId, prePayData } = data
				console.log(data)
				switch (parseInt(payMode)) {

					//现金支付
					case 0:
						p.temp.status.orderSubmitting = false
						wx.hideToast()
						util.goPage('payResult', {
							orderId
						}, true)
					break

					//微信支付
					case 1:
						const { timestamp, nonceStr, signType, paySign } = prePayData
						p.temp.orderId = orderId
						wx.requestPayment({
							timeStamp: timestamp.toString(),
							nonceStr,
							package: prePayData.package,
							signType,
							paySign,
							success: () => {
								p.temp.orderId = ''
								p.temp.status.orderSubmitting = false
								wx.hideToast()
								util.goPage('payResult', {
									orderId
								}, true)
							},
							fail: (err) => {
								console.error(err)
								p.temp.status.orderSubmitting = false
								wx.hideToast()
								if (err.errMsg.indexOf('cancel') == -1) {
									util.error('调用失败', '调用微信支付失败，请点击“提交订单”重试')
								}
								else {
									util.modal('未完成支付', '您还未完成支付，请点击“提交订单”重试')
								}
							}
						})
					break

				}
			},
			fail: (code, msg) => {
				console.error(code, msg)
				p.temp.status.orderSubmitting = false
				wx.hideToast()
				if(code == '-2061') {
					p.temp.orderId = ''
					util.error('订单已过期', '此订单因为超时未支付已经无法支付了哦，请重新点击“确认订单”重新下单')
				}
				else
					util.error('提交失败', `${code} 非常抱歉，订单提交失败，请再次点击“提交订单”重试，如多次尝试仍无法提交请返回清空购物车重新点餐或在小程序内提交用户反馈，谢谢合作`)
			}
		})
    },

    //显示帮助
    showHelp: () => {
        util.modal('优惠规则', '如订单总金额（包含附加物品总金额）低于减免额度时减免将不生效，每个订单只能使用一张活动劵，')
    }

})